using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Web.Routing;

namespace ValidationFramework.Web.MVC.Extensions
{
    internal static class ExtensionsHelper
    {

        /// <summary>
        /// Creates a simple {0}="{1}" list based on current object state.
        /// </summary>
        internal static string CreateAttributeList(RouteValueDictionary attributes)
        {
            var stringBuilder = new StringBuilder();
            if (attributes != null)
            {
                foreach (var keyValuePair in attributes)
                {
                    var attValue = keyValuePair.Value.ToString();

                    if (keyValuePair.Value is bool)
                    {
                        attValue = attValue.ToLowerInvariant();
                    }

                    stringBuilder.AppendFormat(" {0}=\"{1}\" ", keyValuePair.Key.ToLowerInvariant().Replace("_", ""), attValue);
                }
            }
            return stringBuilder.ToString();
        }

        /// <summary>
        /// Creates or appends a 'class' attribute in the supplied dictionary with a given value
        /// </summary>
        /// <param name="htmlAttributes">The <see cref="IDictionary{TKey,TValue}"/> of HTML Attributes</param>
        /// <param name="value">The value to initialize or append to the class attribute</param>
        public static void CreateOrAppendClassAttributeWithValue(ref IDictionary<string, object> htmlAttributes, string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return;
            }

            object classAttrib;

            // If "class" attribute already exists, append it with validationmeta
            if (htmlAttributes.TryGetValue("Class", out classAttrib))
            {
                const string format = "{0} {1}";
                classAttrib = string.Format(format, classAttrib.ToString().TrimEnd(), value);
            }
            else
            {
                classAttrib = value;
            }

            // Replace class attribute in the supplied dictionary with the updated one
            htmlAttributes.Remove("Class");
            htmlAttributes.Add(new KeyValuePair<string, object>("Class", classAttrib.ToString().TrimEnd()));
        }
    }
}